var dir = ["N-", "S-", "W-", "E-"];
var state = [2, 2, 0, 0];
var cycle = [
    ["green-", "yellow-", "red-"], 
    [20, 3, 27],
    ["#60c060", "#d0d060", "#d86060"]
];
var lights = [[], [], [], []];
var timers = [];

// 将各计时器的时间减少 sec
function update(sec) {
    sec %= 50; //一个周期为 50 秒
    for (let pos = 0; pos < 4; pos++) {
        let x = timers[pos].innerHTML - sec;
        if (x <= 0 || x > cycle[1][state[pos]]) {
            lights[pos][state[pos]].style.visibility = "hidden";
            while (x <= 0) {
                state[pos] = (state[pos] + 1) % 3;
                x += cycle[1][state[pos]];
            }
            while (x > cycle[1][state[pos]]) {
                x -= cycle[1][state[pos]];
                state[pos] = (state[pos] + 2) % 3;
            }
            lights[pos][state[pos]].style.visibility = "visible";
            timers[pos].style.color = cycle[2][state[pos]];
        }
        x = (String)(x);
        timers[pos].innerHTML = x.padStart(2, "0"); //"00" ~ "09"
    }
}

for (let pos = 0; pos < 4; pos++) {
    let SIGNAL = document.getElementById(dir[pos] + "signal");

    let timer = document.createElement("div");
    timer.setAttribute("class", "timer");
    timer.setAttribute("id", dir[pos] + "timer");
    timer.innerHTML = state[pos] == 2 ? 25 : cycle[1][state[pos]];
    timer.style.color = cycle[2][state[pos]];
    SIGNAL.appendChild(timer);
    timers.push(timer);

    let LIGHT_BOX = document.createElement("div");
    LIGHT_BOX.setAttribute("class", "light-box " + dir[pos] + "dir");
    LIGHT_BOX.setAttribute("id", dir[pos] + "light-box");
    SIGNAL.appendChild(LIGHT_BOX);

    for (let color = 0; color < 3; color++) {
        let light = document.createElement("div");
        light.setAttribute("class", "light " + cycle[0][color] + "light");
        light.setAttribute("id", dir[pos] + cycle[0][color] + "light");
        if (color == state[pos]) {
            light.style.visibility = "visible";
        } else {
            light.style.visibility = "hidden";
        }
        LIGHT_BOX.appendChild(light);
        lights[pos].push(light);
    }
}

setInterval(update, 1000, 1);